package com.zyc.studentstudy.simple

import android.content.Context
import android.os.Handler
import android.os.Looper
import androidx.annotation.StringRes
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.zyc.studentstudy.utils.ContextHolder
import com.zyc.studentstudy.utils.ResourcesUtil
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus

/**
 * Created by zhangyuncai on 2021/7/29.
 */
open class SimpleVM : ViewModel() {

    val TAG = this::class.java.simpleName

    val mainHandler = Handler(Looper.getMainLooper())

    open val isRegisterEventBus = false

    init {
        if (isRegisterEventBus && !EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }
    }

    fun getContext(): Context {
        return ContextHolder.getApplicationContext()
    }

    open fun runOnUiThread(runnable: Runnable) {
        if (Looper.myLooper() == Looper.getMainLooper()) {
            runnable.run()
        } else {
            mainHandler.post(runnable)
        }
    }

    /**
     * 延时一段时间收到消息
     * @param time 延时时间,毫秒
     * @param callback 延时时间已到回调
     */
    protected fun delayTime(time: Long, callback: ((Boolean) -> Unit)): Job {
        return viewModelScope.launch {
            try {
                delay(time)
                callback.invoke(true)
            } catch (throwable: Throwable) {
            }
        }
    }

    /**
     * @param errorHandler 可自定义错误处理逻辑
     */
    open fun <T> baseLaunch(
        block: suspend CoroutineScope.() -> T,
        errorHandler: suspend (Throwable) -> Unit = {},
        dispatcher: CoroutineDispatcher = Dispatchers.IO
    ): Job {
        return viewModelScope.launch(dispatcher) {
            runCatching {
                block()
            }.onFailure { e ->
                errorHandler.invoke(e)
            }
        }
    }

    fun getString(@StringRes id: Int): String {
        return ResourcesUtil.getString(id)
    }

    override fun onCleared() {
        super.onCleared()
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this)
        }
    }

}
